package priv.abadstring.study.elasticsearch;

import org.apache.commons.io.FileUtils;
import org.apache.http.HttpHost;
import org.apache.http.util.EntityUtils;
import org.elasticsearch.client.Node;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.junit.Test;

import java.io.File;
import java.util.List;

/**
 * SaveMockData
 *
 * @author aBadString
 * @date 2021-08-09 17:52:40
 */
public class SaveMockData {
    @Test
    public void tesBulk() throws Exception {
        RestClientBuilder restClientBuilder = RestClient.builder(
                new HttpHost("abadstring.me", 9200, "http"));
        restClientBuilder.setFailureListener(new RestClient.FailureListener() {
            @Override
            public void onFailure(Node node) {
                System.out.println("出错了 -> " + node);
            }
        });
        RestClient restClient = restClientBuilder.build();

        Request request = new Request("POST", "/haoke/house/_bulk");
        List<String> lines = FileUtils.readLines(new File("D:\\Users\\aBadString\\Desktop\\data.json"), "UTF-8");
        String createStr = "{\"index\": {\"_index\":\"haoke\",\"_type\":\"house\"}}";
        StringBuilder sb = new StringBuilder();
        int count = 0;
        for (String line : lines) {
            sb.append(createStr).append("\n").append(line).append("\n");
            if (count >= 100) {
                request.setJsonEntity(sb.toString());
                Response response = restClient.performRequest(request);
                System.out.println("请求完成 -> " + response.getStatusLine());
                System.out.println(EntityUtils.toString(response.getEntity()));
                count = 0;
                sb = new StringBuilder();
            }
            count++;
        }
        if (!sb.toString().isEmpty()) {
            request.setJsonEntity(sb.toString());
            restClient.performRequest(request);
        }

        restClient.close();
    }
}
